// @ts-check
import fs from 'node:fs'
import chalk from 'chalk'
import { createRequire } from 'node:module'

const require = createRequire(import.meta.url)

export const _targets = fs.readdirSync('packages').filter(f => {
  if (!fs.statSync(`packages/${f}`).isDirectory()) {
    return false
  }

  let pkg
  try {
    pkg = require(`../packages/${f}/package.json`)
  }catch(e){
    console.log(chalk.yellow(`项目${f}不包含package.json，编译忽略`))
    return false
  }
  //const pkg = require(`../packages/${f}/package.json`)
  if (pkg.private && !pkg.buildOptions) {
    return false
  }
  return true
})
console.log(_targets)
export const targets = [
  't-monitor',
  't-plugin-storage',
  't-plugin-crypt',
  't-plugin-ajax',
  't-plugin-ctx',
  't-plugin-api',
  't-plugin-api-fas',
  't-plugin-jsdk-adapter',
].filter((name)=>{ return _targets.includes(name)})

export function fuzzyMatchTarget(partialTargets, includeAllMatching) {
  const matched = []
  partialTargets.forEach(partialTarget => {
    for (const target of targets) {
      if (target.match(partialTarget)) {
        matched.push(target)
        if (!includeAllMatching) {
          break
        }
      }
    }
  })
  if (matched.length) {
    return matched
  } else {
    console.log()
    console.error(
      `  ${chalk.bgRed.white(' ERROR ')} ${chalk.red(
        `Target ${chalk.underline(partialTargets)} not found!`
      )}`
    )
    console.log()

    process.exit(1)
  }
}
